#!/bin/bash

path=`cd "$( dirname ${BASH_SOURCE[0]} )" && pwd`
config=$path/config
bin=$path/bin
yunzai=`cat $config/yunzai.txt`
qs=$path/qs/unidbg-fetch-qsign-1.1.9
devenv=$path/devenv
env=$devenv/system_env

cd $path

source $devenv/system_bin/java8.sh

cd $path

echo "是否更新qs？"
read -p "y or other:" update
if [[ $update == "y" ]];then
	echo "开始更新。"
	cd $qs
	#创建新的本地分区check
	git checkout -b check
	#暂存之前的修改
	git add .
	#将之前的修改提交到 check
	git commit -m "暂存"
	#强制更新本地
	git fetch --all  
	git reset --hard origin/main
	#合并代码到check
	git checkout check  
	git merge main
	cd $path
fi


if [[ ! -d $path/qs  ]];then
	echo "没有安装q签。"
	exit
fi
echo "=========================================================================="
for i in `ls $qs/txlib`
do
	echo $i
done
echo "=========================================================================="
read -p "请选择启动版本（输入上方版本号即可）：" version

if [[ $version == "" || ! -d $qs/txlib/$version ]];then
	echo "未在目录中找到版本：$version，请检查输入是否正确！"
	exit
fi


echo "=========================================================================="
oldPort=`sed -n "/\"port\":/p" $qs/txlib/$version/config.json`
oldPort=${oldPort#*": "}
echo "当前端口号：$oldPort"
echo "是否需要修改端口号？不需要直接回车"
echo "如果需要修改端口号请输入端口号（0-65535）"
echo "推荐端口号大于1w（0-65535）"
echo "=========================================================================="
read -p "请选择：" port
if [[ $port != "" ]];then
	if [[ ! $port =~ ^[0-9]+$ ]];then
		echo "请输入数字，OK？"
		exit
	fi

	if [[ $port < 0 || $port > 65535 ]];then
		echo "端口号超出范围。"
		exit
	fi
else
	port=$oldPort
fi

use=`lsof -i:$port`
use=${use#*"NAME"}
if [[ $use != "" ]];then
	echo "端口已被占用！进程信息："
	echo $use
	echo "是否杀死该进程，以启动qs？"
	echo "如果进程是Miao-Yunzai，请杀死该进程。以重启。"
	read -p "y or other:" op
	if [[ $op == "y" ]];then
		#进程信息
		killPid=${use#*" "}
		#空格去重
		killPid=`echo $killPid | cat`
		#获取PID
		killPid=${killPid%%" "*}
		#杀死进程
		sudo kill -9 $killPid
	else
		exit
	fi
fi

if [[ ! -f $path/$yunzai/config/config/bot.yaml ]];then
	cp $path/$yunzai/config/default_config/bot.yaml $path/$yunzai/config/config/bot.yaml
fi

echo "修改yunzai配置"
sed -i "/sign_api_addr/d" $path/$yunzai/config/config/bot.yaml
echo "sign_api_addr: http://127.0.0.1:$port/sign?key=114514" >> $path/$yunzai/config/config/bot.yaml

echo "修改qs配置文件"
sed -i "s#\"port\": $oldPort#\"port\": $port#g" $qs/txlib/$version/config.json

cd $qs
echo "后台运行qs"
nohup bash bin/unidbg-fetch-qsign --basePath=txlib/$version &
cd $path

echo "正在检测qs是否在运行"
num=0
while true
do
	use=`lsof -i:$port`
	use=${use#*"NAME"}
	if [[ $use != "" ]];then
		echo "qs已启动成功，进程信息："
		echo $use
		break;
	else
		if [[ $num < 4 ]];then
			sleep 5
			((num=$num+1))
			continue
		fi
		echo "qs启动失败。"
		break;
	fi
done

cd $path




